package com.zis.platform.core.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zis.common.Pagination;
import com.zis.common.SearchParams;
import com.zis.platform.common.authentication.UserToken;
import com.zis.platform.common.web.TreeNode;
import com.zis.platform.core.entity.DeptEntity;
import com.zis.platform.core.entity.GroupEntity;
import com.zis.platform.core.entity.RoleEntity;
import com.zis.platform.core.entity.UserEntity;
import com.zis.platform.core.service.DeptService;
import com.zis.platform.core.service.GroupService;
import com.zis.platform.core.service.OrgService;
import com.zis.platform.core.service.RoleService;
import com.zis.platform.core.service.UserService;
import com.zis.util.MD5Salt;
import com.zis.util.Salt;

@Controller
@RequestMapping("/platform/user/")
public class UserAction
{
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private DeptService deptService;
    
    @Autowired
    private GroupService groupService;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private OrgService orgService;
    
    @RequestMapping("list.do")
    public String toUserList()
    {
        return "user/list";
    }
    
    @ResponseBody
    @RequestMapping("list.json")
    public Pagination<UserEntity> list(SearchParams params)
        throws Exception
    {
        Pagination<UserEntity> page = userService.findPageByCondition(params);
        return page;
    }
    
    @ResponseBody
    @RequestMapping("save.json")
    public ModelMap list(@RequestBody
    UserEntity user, ModelMap model)
    {
        UserEntity ru = this.userService.saveOrUpdate(user);
        model.put("state", ru != null);
        return model;
    }
    
    @ResponseBody
    @RequestMapping("list_dept.json")
    public List<DeptEntity> list_dept(SearchParams params)
        throws Exception
    {
        List<DeptEntity> list = this.deptService.findByCondition(params);
        return list;
    }
    
    @ResponseBody
    @RequestMapping("list_orgTree.json")
    public List<TreeNode> list_orgTree(String id)
        throws Exception
    {
        return orgService.findRoot();
    }
    
    @ResponseBody
    @RequestMapping("list_group.json")
    public List<GroupEntity> list_group(SearchParams params)
        throws Exception
    {
        Map<String, Object> searchParams = params.getSearchParams();
        if (searchParams == null)
        {
            searchParams = new HashMap<String, Object>();
        }
        searchParams.put("status", true);
        params.setSearchParams(searchParams);
        List<GroupEntity> list = this.groupService.findByCondition(params);
        return list;
    }
    
    @ResponseBody
    @RequestMapping("list_role.json")
    public List<RoleEntity> list_role(SearchParams params)
        throws Exception
    {
        List<RoleEntity> list = this.roleService.findByCondition(params);
        return list;
    }
    
    @ResponseBody
    @RequestMapping("list_user_role.json")
    public List<RoleEntity> list_user_role(String userId)
        throws Exception
    {
        List<RoleEntity> list = this.userService.findRolesByUserId(userId);
        return list;
    }
    
    @RequestMapping("delete.json")
    @ResponseBody
    public ModelMap add(@RequestBody
    String[] userIds, ModelMap model)
    {
        model.put("state", userService.deleteByUserIds(userIds) > 0);
        return model;
    }
    
    @RequestMapping("enable.json")
    @ResponseBody
    public ModelMap enable(@RequestBody
    String[] userIds, ModelMap model)
    {
        model.put("state", userService.enableByUserIds(userIds) > 0);
        return model;
    }
    
    @RequestMapping("unLock.json")
    @ResponseBody
    public ModelMap unLock(@RequestBody
    String[] userIds, ModelMap model)
    {
        model.put("state", userService.unLockByUserIds(userIds) > 0);
        return model;
    }
    
    @RequestMapping("resetPassword.json")
    @ResponseBody
    public ModelMap resetPassword(@RequestBody
    String[] userIds, ModelMap model)
    {
        model.put("state", userService.resetPasswordByUserIds(userIds) > 0);
        return model;
    }
    
    @RequestMapping("disable.json")
    @ResponseBody
    public ModelMap disable(@RequestBody
    String[] userIds, ModelMap model)
    {
        model.put("state", userService.disableByUserIds(userIds) > 0);
        return model;
    }
    
    @RequestMapping("getById.json")
    @ResponseBody
    public UserEntity getById(@RequestBody
    String userId)
    {
        UserEntity user = this.userService.findById(userId);
        user.setPassword(null);
        user.setSalt(null);
        return user;
    }
    
    @RequestMapping("saveUserRoles.json")
    @ResponseBody
    public ModelMap saveUserRoles(@RequestBody
    UserEntity user, ModelMap model)
    {
        boolean bl = this.userService.saveUserRoles(user);
        model.put("state", bl);
        return model;
    }
    
    @RequestMapping("edit_password.json")
    @ResponseBody
    public ModelMap changPassword(@RequestBody
    Map<String, String> param, ModelMap model)
    {
        String oldPassword = param.get("oldPassword");
        String newPasswrod = param.get("newPasswrod");
        UserToken token = (UserToken)SecurityUtils.getSubject().getPrincipal();
        // 判断原始密码是否匹配
        if (!MD5Salt.compare(oldPassword, token.getUser().getSalt(), token.getUser().getPassword()))
        {
            model.put("state", "error");
            model.put("msg", "原始密码输入错误，请重新输入。");
        }
        else
        {
            String salt = Salt.genRandomL8();
            String enCode = MD5Salt.enCode(newPasswrod, salt);
            UserEntity userEntity = userService.findById(token.getUser().getUserId());
            userEntity.setPassword(enCode);
            userEntity.setSalt(salt);
            userService.saveOrUpdate(userEntity);
            model.put("state", "success");
            model.put("msg", "密码修改成功，请重新登录。");
        }
        return model;
    }
}
